package com.olddriver.crm.web.controller;

import com.olddriver.crm.annotation.PermissionName;
import com.olddriver.crm.domain.Employee;
import com.olddriver.crm.page.PageResult;
import com.olddriver.crm.query.EmployeeQueryObject;
import com.olddriver.crm.service.IEmployeeService;
import com.olddriver.crm.util.JsonResult;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.DateTime;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.List;

@Controller
@RequestMapping("employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    @RequestMapping("list")
    @RequiresPermissions("employee:list")
    @PermissionName("查看员工")
    public String list() {
        return "employee/list";
    }

    @RequestMapping("selectAllEmployees")
    @ResponseBody
    public Object selectAllEmployees() throws Exception{
        List<Employee> employees = employeeService.selectAllEmployees();
        return employees;
    }

    @ResponseBody
    @RequestMapping("query")
    @RequiresPermissions("employee:query")
    @PermissionName("员工列表")
    public PageResult query(EmployeeQueryObject qo) {
        PageResult result = employeeService.query(qo);
        return result;
    }

    @ResponseBody
    @RequestMapping("saveOrUpdate")
    @RequiresPermissions("employee:saveOrUpdate")
    @PermissionName("员工编辑")
    public JsonResult saveOrUpdate(Employee employee) {
        Long id = employee.getId();
        try {
            if (id != null) {
                employeeService.update(employee);
            } else {
                employee.setState(true);
                employeeService.insert(employee);
            }
            return JsonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.faliure();
        }
    }

    //主页顶部修改个人信息的Controller
    @ResponseBody
    @RequestMapping("personalUpdate")
    public JsonResult personalUpdate(Employee employee, String oldpassword) {
        Long id = employee.getId();
        Employee principal = (Employee) SecurityUtils.getSubject().getPrincipal();
        String dataBasePassword = new Md5Hash(oldpassword, principal.getUsername(), 2).toString();

        if (!dataBasePassword.equals(principal.getPassword())) {
            return JsonResult.diyFaliure("原密码错误");
        }
        try {
            if (id != null) {
                employee.setUsername(principal.getUsername());
                employeeService.updateProfile(employee);
            }
            return JsonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.faliure();
        }
    }

    @ResponseBody
    @RequestMapping("changeState")
    @RequiresPermissions("employee:changeState")
    @PermissionName("员工状态变更")
    public JsonResult changeState(Boolean state, Long id) {
        try {
            employeeService.updateState(state, id);
            return JsonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.faliure();
        }
    }

    @ResponseBody
    @RequestMapping("import")
    @RequiresPermissions("employee:import")
    @PermissionName("员工导入")
    public JsonResult importEmployee(MultipartFile file) throws Exception {
        Workbook workbook = Workbook.getWorkbook(file.getInputStream());
        Sheet sheet = workbook.getSheet(0);
        int rows = sheet.getRows();
        if (rows > 1) {
            for (int i = 1; i < rows; i++) {
                Employee employee = new Employee();
                employee.setUsername(sheet.getCell(0, i).getContents());
                employee.setRealname(sheet.getCell(1, i).getContents());
                employee.setTel(sheet.getCell(2, i).getContents());
                employee.setEmail(sheet.getCell(3, i).getContents());
                /*部门需要设置ID*/
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                employee.setInputTime(format.parse(sheet.getCell(5, i).getContents()));
                employee.setState(Boolean.parseBoolean(sheet.getCell(6, i).getContents()));
                employeeService.insert(employee);
            }
        }
        workbook.close();
        return JsonResult.success();
    }

    @RequestMapping("export")
    @RequiresPermissions("employee:export")
    @PermissionName("员工导出")
    public void exportEmployee(EmployeeQueryObject qo, HttpServletResponse resp) throws Exception {
        resp.setHeader("Content-Disposition", "attachment;filename=employee.xls");
        List<Employee> employees = employeeService.listAll(qo);
        if (employees != null && employees.size() != 0) {
            WritableWorkbook workbook = Workbook.createWorkbook(resp.getOutputStream());
            WritableSheet sheet = workbook.createSheet("员工列表", 0);
            sheet.addCell(new Label(0, 0, "用户名"));
            sheet.addCell(new Label(1, 0, "真实姓名"));
            sheet.addCell(new Label(2, 0, "电话"));
            sheet.addCell(new Label(3, 0, "邮箱"));
            sheet.addCell(new Label(4, 0, "部门"));
            sheet.addCell(new Label(5, 0, "入职时间"));
            sheet.addCell(new Label(6, 0, "员工状态"));
            int i = 1;
            for (Employee employee : employees) {
                sheet.addCell(new Label(0, i, employee.getUsername()));
                sheet.addCell(new Label(1, i, employee.getRealname()));
                sheet.addCell(new Label(2, i, employee.getTel()));
                sheet.addCell(new Label(3, i, employee.getEmail()));
                if (employee.getDept() != null) {
                    sheet.addCell(new Label(4, i, employee.getDept().getName()));
                }
                if (employee.getInputTime() != null) {
                    sheet.addCell(new DateTime(5, i, employee.getInputTime()));
                } else {
                    sheet.addCell(new Label(5, i, ""));
                }
                if (employee.getState() != null) {
                    sheet.addCell(new Label(6, i, employee.getState() ? "在职" : "离职"));
                } else {
                    sheet.addCell(new Label(6, i, ""));
                }
                i++;
            }

            workbook.write();
            workbook.close();
        }
    }


    @RequestMapping("exportTemplate")
    public void exportTemplate(HttpServletResponse resp) throws Exception {
        resp.setHeader("Content-Disposition", "attachment;filename=employee.xls");
        WritableWorkbook workbook = Workbook.createWorkbook(resp.getOutputStream());
        WritableSheet sheet = workbook.createSheet("员工列表", 0);
        sheet.addCell(new Label(0, 0, "用户名"));
        sheet.addCell(new Label(1, 0, "真实姓名"));
        sheet.addCell(new Label(2, 0, "电话"));
        sheet.addCell(new Label(3, 0, "邮箱"));
        sheet.addCell(new Label(4, 0, "部门ID"));
        sheet.addCell(new Label(5, 0, "入职时间"));
        sheet.addCell(new Label(6, 0, "员工状态"));

        workbook.write();
        workbook.close();
    }
}
